/**
 * 
 */
package com.littleken.browser.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.littleken.browser.utils.SimpleResponse;
import com.littleken.core.config.loginType;
import com.littleken.core.config.SecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录失败跳转逻辑
 */
@Component("littlekenAuthenctiationFailureHandler")
@Slf4j
public class littlekenAuthenctiationFailureHandler  extends SimpleUrlAuthenticationFailureHandler{

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private SecurityProperties securityproperties;

    /**
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param e 登录错误信息
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        //log.error("登录失败");
        if(loginType.JSON.equals(securityproperties.getBrowser().getLogintype())){
            httpServletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            httpServletResponse.setContentType("application/json;charset=UTF-8");
            httpServletResponse.getWriter().write(objectMapper.writeValueAsString(new SimpleResponse(e.getMessage())));//返回错误信息
        }else {
            super.onAuthenticationFailure(httpServletRequest, httpServletResponse,e);
        }

    }
}
